<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ul>
        <li><a href="/home">首页</a></li>
        <li><a href="/about">关于</a></li>
    </ul>

    <div id="root"></div>

    <script>
        const routes =[
            {
                path:'/home',
                component:()=>{
                    return `<h1>首页</h1>`
                },
            },
            {
                path:'/about',
                component:()=>{
                    return `<h1>关于</h1>`
                }
            }
        ]

        let routerView =document.getElementById('root');

        window.addEventListener('DOMContentLoaded',(e)=>{
            onLoad()
        })
        window.addEventListener('popstate',(e)=>{
            renderView(location.pathname);
        })

        function onLoad(){ //渲染对应组件
            let linkList =document.querySelectorAll('a[href]');//进入浏览器的缓存栈，但是不受前进后退的影响
            linkList.forEach(el =>{
                el.addEventListener('click',(e)=>{
                    e.preventDefault(); //阻止默认行为
                    let url =el.getAttribute('href');
                    
                    history.pushState(null,'',url);
                    renderView(location.pathname);
                })
            })
        }
        function renderView(url){
            let index =routes.findIndex(item=>{
                return item.path === url;
            })
            routerView.innerHTML = routes[index].component();
        }

    </script>
</body>
</html>